package com.idea.dsl.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.idea.dsl.config.DslProperties;
import com.idea.dsl.model.ModelRequest;
import com.idea.dsl.model.ModelResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Claude客户端实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ClaudeClient implements ModelClient {
    
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    private final DslProperties dslProperties;
    
    private static final String CLIENT_TYPE = "claude";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    
    @Override
    public ModelResponse chat(ModelRequest request) {
        try {
            DslProperties.ModelConfig config = dslProperties.getModels().get(CLIENT_TYPE);
            if (config == null) {
                throw new RuntimeException("Claude配置未找到");
            }
            
            // 转换为Claude格式
            Map<String, Object> claudeRequest = convertToClaudeFormat(request, config);
            String requestBody = objectMapper.writeValueAsString(claudeRequest);
            log.debug("Claude请求: {}", requestBody);
            
            // 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(config.getBaseUrl() + "/messages")
                    .header("x-api-key", config.getApiKey())
                    .header("Content-Type", "application/json")
                    .header("anthropic-version", "2023-06-01")
                    .post(RequestBody.create(requestBody, JSON))
                    .build();
            
            // 发送请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    throw new RuntimeException("Claude请求失败: " + response.code() + " " + response.message());
                }
                
                String responseBody = response.body().string();
                log.debug("Claude响应: {}", responseBody);
                
                return convertFromClaudeFormat(responseBody);
            }
            
        } catch (IOException e) {
            log.error("Claude请求异常", e);
            throw new RuntimeException("Claude请求异常: " + e.getMessage(), e);
        }
    }
    
    private Map<String, Object> convertToClaudeFormat(ModelRequest request, DslProperties.ModelConfig config) {
        Map<String, Object> claudeRequest = new HashMap<>();
        claudeRequest.put("model", config.getModel());
        claudeRequest.put("max_tokens", request.getMaxTokens() != null ? request.getMaxTokens() : config.getMaxTokens());
        claudeRequest.put("messages", request.getMessages());
        
        if (request.getTemperature() != null) {
            claudeRequest.put("temperature", request.getTemperature());
        }
        
        return claudeRequest;
    }
    
    private ModelResponse convertFromClaudeFormat(String responseBody) throws IOException {
        // 这里需要根据Claude的实际响应格式进行转换
        // 简化实现，实际使用时需要根据Claude API文档调整
        Map<String, Object> claudeResponse = objectMapper.readValue(responseBody, Map.class);
        
        return ModelResponse.builder()
                .id((String) claudeResponse.get("id"))
                .model((String) claudeResponse.get("model"))
                .build();
    }
    
    @Override
    public String getClientType() {
        return CLIENT_TYPE;
    }
    
    @Override
    public boolean isAvailable() {
        DslProperties.ModelConfig config = dslProperties.getModels().get(CLIENT_TYPE);
        return config != null && StringUtils.isNotBlank(config.getApiKey());
    }
}
